//
//  MineViewController.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 16/11/29.
//  Copyright © 2016年 com.xtion.crm. All rights reserved.
//

#import "MineViewController.h"
#import "CollectionViewCell.h"
#import "MyInfoViewController.h"
#import "HeadImageView.h"
#import "ModifyPwdViewController.h"
#import "AboutUsViewController.h"
#import "OnlineUserViewController.h"
#import "SynDataViewController.h"

#import "AddSimpleViewController.h"
#import "SimpleCollectionViewCell.h"

NSString const *MineViewControllerMenuCodeParamKey = @"MineViewControllerMenuCodeParamKey";

@interface MineViewController ()<HeadImageViewDelegate,XUIGroupTableViewDelegate,XUIGroupTableViewDataSource,SimpleCollectionViewCellDelegate>
{
    NSMutableArray *_qdData;
    RSWDataOperation *_manager;
    
    UILabel *_nameLabel;
    
    UIImageView *_navBarHairlineImageView;
    
    HeadImageView *_headImageView;
    
    UIFont *_titleFont;
    
    NSString *_logoURL;
    
    XUIButton *_modifyBtn;
    
    NSInteger itemCount;
    CGSize itemSize;
    
    XUIGroupTableView *_gtable;
}
@end

@implementation MineViewController

- (void)viewDidLoad {
    //[[XUINavigationController navigationController] setNavigationBarHidden:YES animated:YES];
    [super viewDidLoad];
    [self checkSession];
    
    [self setBackNavigateItemTitle:@"个人中心" rightItemImageName:@"img_exit"];
    self.navigationItem.leftBarButtonItem = nil;
    
    self.view.backgroundColor = [UIColor colorWithHex:mcrmSAASUISkinColorTextStylef1f4f7Color];
    
    [self initVariable];
    
    NSString *_code = self.param[MineViewControllerMenuCodeParamKey];
    [self addMainThreadObserverWithDictionarySelector:@{CurrentUserCurrentUserHeadImageUpdateNotification:@"observerCurrentUserCurrentUserHeadImageUpdateNotification:"}];
    [self addKeyboardObserver];
    
    [self initUI];
    
    [_manager getSubMenuListByParentCode:_code Completion:^(NSInteger nResult, NSArray *output, NSError *error) {
        [self requestComplete:nil result:nResult output:output error:error];
    }];
}

- (void)initVariable
{
    _qdData = [NSMutableArray new];
    _titleFont =[UIFont new];
    _logoURL = @"";
    
    _navBarHairlineImageView = [self findHairlineImageViewUnder:[XUINavigationController navigationController].navigationBar];
    
    _manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:self];
    
    if([UIDevice is40InchScreen] == YES)
    {
        itemCount = 3;
        itemSize = CGSizeMake(80, 80);
    }
    else
    {
        itemCount = 3;
        itemSize = CGSizeMake(100, 100);
    }
}

- (void)initUI
{
    UIView *backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height/3 + 35)];
    backView.backgroundColor = [UIColor colorWithHex:mcrmSAASUIShinColorTextStyle2196F3Color];
    
    [self.view addSubview:backView];
    
    if(_nameLabel == nil)
    {
        _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, backView.bottom - 30, self.view.width, 30)];
        _nameLabel.text = [MyInfo myInfo].userName;
        _nameLabel.textColor = [UIColor whiteColor];
        
        _nameLabel.textAlignment = NSTextAlignmentCenter;
        
        [backView addSubview:_nameLabel];
    }
    
    if(_headImageView == nil)
    {
        _headImageView = [[HeadImageView alloc]initWithFrame:CGRectMake(13, 0, 90, 90) userInteractionEnabled:YES];
        _headImageView.delegate = self;
        _headImageView.headImage = [CCurrentUser currentUserHeadImage];
        _headImageView.layer.cornerRadius = 45;
        _headImageView.layer.masksToBounds = YES;
        //_headImageView.layer.borderWidth = 1.5;
        //_headImageView.layer.borderColor = [[UIColor whiteColor] CGColor];
        _headImageView.tag = 10000;
        _headImageView.centerX = [UIDevice screenWidth]/2;
        
        _headImageView.bottom = _nameLabel.top - 10;
        [backView addSubview:_headImageView];
    }
    
    _gtable = [[XUIGroupTableView alloc]initWithFrame:CGRectMake(0, _nameLabel.bottom, self.view.width, (self.view.height - 49)  -  (_nameLabel.bottom))];
    _gtable.backgroundColor = [[UITableView appearance] backgroundColor];
    _gtable.delegate = self;
    _gtable.dataSource = self;
    
    [self.view addSubview:_gtable];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    _navBarHairlineImageView.hidden = YES;
}

//- (void)viewWillDisappear:(BOOL)animated
//{
//    [super viewWillDisappear:animated];
//    
//    _navBarHairlineImageView.hidden = NO;
//}

-(void)viewControllerWillDealloc
{
    [super viewControllerWillDealloc];
    
    [_manager terminateRequest];
    
    [self removeObserver];
}

-(void)requestComplete:(XMSDataOperationManager *)dom result:(NSInteger)nResult output:(id)output error:(NSError *)error
{
    [self filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
     {
         switch(requestResult)
         {
             case YES:
             {
                 NSArray *arr = output;
                 for(MenuInfo *info in arr)
                 {
                     if([info.name isEqualToString:@"自动更新"])
                         continue;
                     [_qdData addObject:info];
                 }
                 
                 MenuInfo *testInfo = [MenuInfo new];
                 testInfo.pId = @"100";
                 testInfo.code = @"测试";
                 testInfo.name = @"测试";
             
                 [_qdData addObject:testInfo];
                 
                 [_gtable reloadData];
                 
                 break;
             }
             default:
             {
                 break;
             }
         }
     }];
}

#pragma mark --
#pragma mark -- XUIGroupTableViewDelegate XUIGroupTableViewDataSource
-(CGFloat)groupTableView:(XUIGroupTableView *)groupTableView heightForHeaderInGroup:(NSInteger)group
{
    return 0;
}

- (NSUInteger)numberOfGroupsInGroupTableView:(XUIGroupTableView *)groupTableView
{
    return 1;
}

- (NSUInteger)groupTableView:(XUIGroupTableView *)groupTableView numberOfRowsInGroup:(NSInteger)group
{
    return 1;
}

- (CGFloat)groupTableView:(XUIGroupTableView *)groupTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row ==0)
    { 
        return _gtable.height;
    }
    
    return 44;
}

- (XUIGroupTableViewCell *)groupTableView:(XUIGroupTableView *)groupTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SimpleCollectionViewCell *cell = [[SimpleCollectionViewCell alloc] initWithFrame:CGRectZero];
    cell.backgroundColor = [UIColor whiteColor];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.itemCount = 4;
    cell.uiEdgeInsets = UIEdgeInsetsMake(1, 1, 1, 1);
    cell.title = @"";
    cell.hiddenTitle = YES;
    cell.delegate = self;
    cell.qdData = [_qdData mutableCopy];
    
    return cell;
}

#pragma --
#pragma -- SimpleCollectionViewCellDelegate
-(void)simpleCollectionViewCell:(SimpleCollectionViewCell*)cell clickedButton:(id)sender info:(MenuInfo*)info;
{
    if([info.code isEqualToString:@"个人信息"])
    {
        XUIViewControllerSwitchParam *p = [XUIViewControllerSwitchParam new];
        p.param[MyInfoViewControllerTitleParamKey] =  info.name;
        
        [XUINavigationController pushViewControllerClass:[MyInfoViewController class] withSwitchParam:p];
    }
    else if([info.code isEqualToString:@"修改密码"])
    {
        XUIViewControllerSwitchParam *p = [XUIViewControllerSwitchParam new];
        p.param[ModifyPwdViewControllerTitleParamKey] =  info.name;
        
        [XUINavigationController pushViewControllerClass:[ModifyPwdViewController class] withSwitchParam:p];
    }
    else if([info.code isEqualToString:@"测试"])
    {
        [XUINavigationController pushViewControllerClass:[AddSimpleViewController class]];
    }
    else if([info.code isEqualToString:@"关于我们"])
    {
        XUIViewControllerSwitchParam *p = [XUIViewControllerSwitchParam new];
        p.param[AboutUsViewControllerTitleParamKey] =  info.name;
        
        [XUINavigationController pushViewControllerClass:[AboutUsViewController class] withSwitchParam:p];
    }
    else if([info.code isEqualToString:@"自动更新"])
    {
        [self checkVersion];
    }
    else if([info.code isEqualToString:@"在线人员"])
    {
        XUIViewControllerSwitchParam *p = [XUIViewControllerSwitchParam new];
        p.param[OnlineUserViewControllerTitleParamKey] =  info.name;
        
        [XUINavigationController pushViewControllerClass:[OnlineUserViewController class] withSwitchParam:p];
    }
    else if([info.code isEqualToString:@"数据同步"])
    {
        XUIViewControllerSwitchParam *p = [XUIViewControllerSwitchParam new];
        p.param[SynDataViewControllerTitleParamKey] =  info.name;
        
        [XUINavigationController pushViewControllerClass:[SynDataViewController class] withSwitchParam:p];
    }
}

#pragma mark --
#pragma mark -- observer
-(void)observerCurrentUserCurrentUserHeadImageUpdateNotification:(NSNotification*)noti
{
    _headImageView.headImage = [CCurrentUser currentUserHeadImage];
}

-(void)clickHeadImageView:(HeadImageView*)headImageView
{
    [XUIActionSheetView actionSheetViewWithTitle:@"t" cancelButtonTitle:@"取消" otherButtonTitles:@[@"拍照",@"从相册选择"] show:^(NSUInteger clickIndex)
     {
         if (clickIndex == 0)
             [self choicePhotoWithMaxCount:1 sourceType:UIImagePickerControllerSourceTypeCamera];
         else
             [self choicePhotoWithMaxCount:1 sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
     }];
}

#pragma mark --
#pragma mark -- 图片处理
- (void)imageOperation:(NSArray *)images
{
    DispatchGlobalThreadAsync(^{
        [self beginProgressViewPanel:@"图片处理中"];
        
        UIImage *newImage = images[0];
        NSString *guid = [XMSGUID GUIDLowString];
        NSString *filename = [NSString stringWithFormat:@"%@.jpg", guid];
        NSString *path = [[XMSFileHelper tempPath] stringByAppendingPathComponent:filename];
        
        [UIImageJPEGRepresentation(newImage, 1) writeToFile:path atomically:NO];
        [UIImage imageFileSize:[XMSFileHelper getFileSize:path] imageSize:newImage.size compressParam:^(CGFloat zoomMultiple,CGSize zoomSize,CGFloat quality)
         {
             CGSize size = zoomSize;
             UIImage *image = [UIImage imageFromImage:newImage scaledToSize:size];
             
             //保存原始照片到本地
             NSData *data = UIImageJPEGRepresentation(image, quality);
             [data writeToFile:path atomically:NO];
         }];
        
        if(_manager == nil)
            _manager = [[RSWDataOperation alloc] initWithDataOperationManagerDelegate:self];
        
        [self setProgressViewPanelReleaseDelayTime:1];
        
        NSArray *fileIdArray = [_manager uploadImage:@[path] paras:nil];
        if(fileIdArray.count > 0)
        {
            _logoURL = fileIdArray[0];
        }
        
        [_manager modifyUserHeadImage:path logoURL:_logoURL completion:^(NSInteger nResult, BOOL bResult, NSError *error)
         {
             [self filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
              {
                  switch(requestResult)
                  {
                      case YES:
                      {
                          _headImageView.headImage = [CCurrentUser currentUserHeadImage];
                          break;
                      }
                      default:
                      {
                          [UIAlertView showErrorMsg:@"上传头像失败"];
                          break;
                      }
                  }
              }];
         }];
        
        [self endProgressViewPanel];
    });
}

#pragma mark --
#pragma mark -- 进度条
-(void)beginProgressView:(XMSDataOperationManager *)dom funcationName:(NSString *)szFuncationname
{
    if([szFuncationname isEqualToString:@"modifyUserHeadImage"])
    {
        [self beginProgressViewPanel:@"头像上传中"];
    }
    else
        [super beginProgressView:dom funcationName:szFuncationname];
}

-(void)clickedRightBarButton:(id)sender
{
    [XUIActionSheetView actionSheetViewWithTitle:@"" cancelButtonTitle:@"取消" otherButtonTitles:@[@"注销"] show:^(NSUInteger clickIndex)
     {
         if(clickIndex == 0)
         {
             [NSNotificationCenter postNotification:MainViewControllerExitNotification];
         } 
     }];
}

#pragma --
#pragma checkVersion
- (void)checkVersion
{
    [XLGCheckNewVersion checkNewVersion:self completion:^(NSInteger nResult)
     {
         switch(nResult)
         {
             case XLGCheckNewVersionForceUpdateCode:
             case XLGCheckNewVersionSuggestUpdateCode:
             {
                 [XLGContext remindNewVersion:YES];
                 [NSNotificationCenter postNotification:XLGCheckNewVersionXLGCheckNewVersionResultNotification userInfo:@{XLGCheckNewVersionXLGCheckNewVersionResultNewKey:@(YES)}];
                 break;
             }
             case YES:
             {
                 [UIAlertView showInfoMsg:@"已是最新版本"];
                 break;
             }
             case TERMINATEREADWRITE:
             {
                 break;
             }
             default:
             {
                 [UIAlertView showErrorMsg:@"检查失败"];
                 break;
             }
         }
     }];
}
@end
